package com.bz.common;

import java.util.List;
import java.util.StringJoiner;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import lombok.extern.slf4j.Slf4j;

@RestControllerAdvice
@Slf4j
public class GloubExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseDto<String> Execption(Exception e) {
        log.error("未知异常！", e);
        return new ResponseDto<>(Codeenum.ERROR);
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseDto<String> BusinessException(BusinessException e) {
        log.error("业务异常！", e);
        return new ResponseDto<>(Codeenum.ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseDto<String> MissingServletRequestParameterException(MissingServletRequestParameterException e) {
        return new ResponseDto<>(Codeenum.PARAM_ERROR.getCode(), Codeenum.PARAM_ERROR.getMsg() + ":" + e.getParameterName());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseDto<String> MethodArgumentNotValidException(MethodArgumentNotValidException e) {

        StringJoiner sj = new StringJoiner(",");

        List<FieldError> efs = e.getBindingResult().getFieldErrors();
        if (!CollectionUtils.isEmpty(efs)) {
            for (FieldError ef : efs) {
                sj.add(ef.getField() + " " + ef.getDefaultMessage());
            }
        }

        return new ResponseDto<>(Codeenum.PARAM_ERROR.getCode(), sj.toString());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseDto<String> HttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return new ResponseDto<>(Codeenum.PARAM_ERROR.getCode(), e.getMessage());
    }

    /**
     * @desc: 服务不存在
     * @return: 异常信息
     */
    @ExceptionHandler(value = NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseDto<String> errorHandler(HttpServletRequest request,
                                            NoHandlerFoundException exception,
                                            HttpServletResponse response,
                                            Exception e) {
        return new ResponseDto<>(Codeenum.NOT_FIND);
    }
}
